#include "container/windows/windowcontainer.h"
#include "./hovertrigger.h"
#include "./winview.h"

using namespace MiniUI;
using namespace MiniUI::Type;

const char* DeriveUIObject<WinView, View>::s_szTypeName = "WinView";

WinView::WinView()
: m_pObjFocus(nullptr)
{
    m_pWinView = this;
    m_pHoverTrigger = new HoverTrigger();
    m_pContainer = WindowContainer::CreateInstance();
}

WinView::~WinView()
{
    delete m_pHoverTrigger;
    m_pContainer->Release();
}

void WinView::OpenWindow(const MiniRect& rcWnd)
{
    FakeUpdateRect(rcWnd);

    m_pContainer->CreateContainer(rcWnd);
    m_pContainer->Bind(this);
    m_pContainer->Show();
}

void WinView::GetScreenCursorPos(MiniPoint& pt)
{
    m_pContainer->GetCursorPos(pt);
}

void* WinView::GetHost()
{
    return m_pContainer->GetHost();
}

void WinView::SetCursor(CursorType cursor, void* customCursor)
{
    m_pContainer->SetCursor(cursor, customCursor);
}

void WinView::SetWinBorder(const MiniRect& rcBorder)
{
    m_pContainer->SetBorder(rcBorder);
}

bool WinView::SetFocusObject(UIObject* pObj)
{
	if (m_pObjFocus != pObj)
	{
		if (m_pObjFocus)
		{
			m_pObjFocus->DoFocusChange(false);
		}
		m_pObjFocus = pObj;
		if (m_pObjFocus)
		{
			m_pObjFocus->DoFocusChange(true);
		}
	}
	return true;
}

UIObject* WinView::GetFocusObject()
{
	return m_pObjFocus;
}

void WinView::DoWindowActivate(bool bActivate)
{
    DoFireEvent(OnWindowActivateEventFunc, OnWindowActivate, (this, bActivate));
}

bool WinView::AddChild(UIObject* pChild)
{
    if (View::AddChild(pChild))
    {
        if (pChild->GetWinView())
        {
            //should not have a app view.
            ::DebugBreak();
            return false;
        }
        pChild->SetWinView(this);
        return true;
    }
    return false;
}

int WinView::InsertChild(int nPos, UIObject* pChild)
{
    int nIndex = View::InsertChild(nPos, pChild);
    if (nIndex != -1)
    {
        if (pChild->GetWinView())
        {
            //should not have a app view.
            ::DebugBreak();
            return -1;
        }
        pChild->SetWinView(this);
        return nIndex;
    }
    return -1;
}

HoverTrigger* WinView::GetHoverTrigger()
{
    return m_pHoverTrigger;
}

void WinView::FakeUpdateRect(const Type::MiniRect& rcWnd)
{
    this->SetSize(rcWnd.Size());
    this->SetMargin(rcWnd);

    RECT rcWork = {0, 0, 0, 0};
    ::SystemParametersInfo(SPI_GETWORKAREA, 0, &rcWork, 0);
    MiniRect rc(rcWork.left, rcWork.top, rcWork.right, rcWork.bottom);

    View* pFakeView = View::CreateInstance();
    pFakeView->SetRect(rc);
    pFakeView->DoLayout();
    this->UpdateRect(pFakeView);
    pFakeView->Release();
}